/**
	httpuserdb.cpp
	~~~~~~~~~~~~~~~~~~~~~~~~~


	Copyright (c) 2007-2008 <ptthippo@gmail.com>

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
#include "../common/config.h"
#include <md5.h>
#include <fstream>
#include <iostream>
#include "httpuserdb.h"

using namespace std;

template< class T >
inline T const& as_const( T const& r )
{
    return r;
}

void md5_hash(unsigned char *hash, const char* password, size_t size)
{
	md5_state_t state;
	md5_byte_t digest[16];

	md5_init(&state);
	md5_append(&state, (const md5_byte_t *)password, size);
	md5_finish(&state, digest);

	memcpy(hash, digest, 16);
}

HTTPUserDB::HTTPUserDB(const string & filename)
	: m_filename(filename)
{
}

bool HTTPUserDB::loadDB()
{
	ifstream ifs(m_filename.c_str(), ios::binary);

	if(ifs.good() == false)
	{
		return false;
	}

	boost::archive::text_iarchive ia(ifs);
	try
	{
		ia >> *this;
	}
	catch(...)
	{
		throw;
	}

	return true;
}

bool HTTPUserDB::saveDB()
{
	ofstream ofs(m_filename.c_str());

	if(ofs.good() == false)
	{
		return false;
	}
	
	try
	{
		boost::archive::text_oarchive oa(ofs);
		oa << as_const(*this);
	}
	catch(...)
	{
		throw;
	}

	return true;
}

int HTTPUserDB::addUser(const HTTPUser & user)
{
	string pass;
	unsigned char md5_pass[16];

	pass = user.getPassword();
	md5_hash(md5_pass, pass.c_str(), pass.size());

	pass.assign((const char*)md5_pass, 16);
	HTTPUser *clone = new HTTPUser(user);
	clone->setPassword(pass);
	string username = user.getUsername();
	pair<USER_ITER, bool> ret = m_users.insert(username, clone);
	if(ret.second == false)
	{
		delete clone;
		return ERROR_USEREXISTED;
	}
	return SUCCESS;
}

int HTTPUserDB::delUser(const string & name)
{
	USER_ITER iter = m_users.find(name);
	if(iter == m_users.end())
		return ERROR_USERNOTFOUND;

	m_users.erase(iter);
	return SUCCESS;
}

boost::shared_ptr<HTTPUser> HTTPUserDB::getUser(const string & name)
{
	boost::shared_ptr<HTTPUser> ret;

	USER_ITER iter = m_users.find(name);
	if(iter != m_users.end())
	{
		ret = boost::shared_ptr<HTTPUser>(new HTTPUser(*(iter->second)));
	}
	
	return ret;
}

vector<string> HTTPUserDB::getAllUsername()
{
	vector<string> ret;
	for(USER_ITER iter = m_users.begin(); iter != m_users.end(); iter++)
	{
		ret.push_back(iter->first);
	}
	return ret;
}

int HTTPUserDB::authUser(const string & username, const string & password)
{
	boost::shared_ptr<HTTPUser> ptr = getUser(username);

	if(!ptr)
		return ERROR_USERNOTFOUND;

	char md5_pass[16];
	md5_hash((unsigned char*)md5_pass, password.c_str(), password.size());
	
	if(equal(md5_pass, md5_pass+16, ptr->getPassword().begin()))
		return SUCCESS;

	return ERROR_AUTHFAIL;
}

template<class Archive>
void HTTPUserDB::save(Archive & ar, const unsigned int version) const
{
	ar & m_users;
}

template<class Archive>
void HTTPUserDB::load(Archive & ar, const unsigned int version)
{
	ar & m_users;
}

